package com.mock.ems.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.mock.base.util.CollectionUtil;
import com.mock.base.util.StringUtil;
import com.mock.ems.config.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提现申请
 * @author whx
 * @date 2017/08/19
 */
public class FeedBackController extends Controller {
    public void index()  {
        renderJsp("/page/feedback/feedback_list.jsp");
    }

    public void pagination() {
        int limit = getParaToInt("limit");
        int offset = getParaToInt("offset");
        int pageNumber = (offset / limit) + 1;

        StringBuilder sqlExceptSql = new StringBuilder(" from user_feedback where 1 = 1");
        List<Object> params = new ArrayList<Object>();
        String selectSql = "select *";

        String nickName = getPara("nick_name", "");
        if (StringUtil.isNotEmpty(nickName.trim())) {
            sqlExceptSql.append( " and nick_name like ?");
            params.add("%" + nickName.trim() + "%");
        }

        int status = getParaToInt("status", -1);
        if (status != -1) {
            sqlExceptSql.append(" and status = ?");
            params.add(status);
        }

        Page<Record> recordList = Db.paginate(pageNumber, limit, selectSql, sqlExceptSql.toString(), params.toArray());

        if(CollectionUtil.isNotEmpty(recordList.getList())){
            recordList.getList().stream().forEach(item->{
                Long userId = item.getLong("user_id");
                Record user = UserManager.getUser(userId);
                if(user == null){
                    user = Db.findById("user",userId);
                    if(user != null){
                        UserManager.setUser(user);
                    }
                }
                item.set("nick_name",user == null ? "未知" : user.getStr("nick_name"));
            });
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }

    public void image(){

        Long feedbackId = getParaToLong("feedbackId");
        Record feedback = Db.findById("user_feedback",feedbackId);
        setAttr("feedback",feedback);

        renderJsp("/page/feedback/feedback_image.jsp");
    }
}
